package com.lincoln.framework.interceptor;

import com.lincoln.framework.annotation.UnAuth;
import com.lincoln.framework.common.ApiCode;
import com.lincoln.framework.common.ApiMessageHandler;
import com.lincoln.framework.common.ChecksumUtils;
import com.lincoln.framework.utils.FrameworkLogger;
import com.lincoln.framework.utils.StringUtilsEx;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * api拦截校验
 */
public class ApiAuthInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 日志
	 */
	private static FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(ApiAuthInterceptor.class);

	/**
	 * 拦截器校验
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		logger.debug("api请求参数：" + StringUtilsEx.toJsonString(request.getParameterMap()));
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		if (handlerMethod.getMethod().isAnnotationPresent(UnAuth.class)) {
			return true;
		}

		Class clasz = handlerMethod.getBean().getClass();
		if (clasz.isAnnotationPresent(UnAuth.class)) {
			return true;
		}

		String checksum = request.getParameter("checksum");
		if (StringUtilsEx.isNullOrEmpty(checksum)) {
			returnErrorData(ApiCode.CHECKSUM_LACK, request, response);
			return false;
		}

		Map<String, String[]> paramsMap = request.getParameterMap();
		String encodeCheckSum = ChecksumUtils.getCheckSum(paramsMap);

		if (!encodeCheckSum.toLowerCase().equals(checksum.toLowerCase())) {
			returnErrorData(ApiCode.CHECKSUM_WRONG, request, response);
			return false;
		}
		return true;
	}

	public static void main(String[] args) {
		Map<String, String[]> paramsMap = new HashMap<String,String[]>(){{
			this.put("memberId", new String[]{"25"});
		}};
		
		System.out.println(ChecksumUtils.getCheckSum(paramsMap));
	}
	
	/**
	 * 返回错误信息
	 * 
	 * @param apiCode
	 * @param request
	 * @param response
	 */
	private void returnErrorData(int apiCode, HttpServletRequest request, HttpServletResponse response) {
		ApiMessageHandler apiMessageHandler = new ApiMessageHandler(request, response);
		apiMessageHandler.returnData(apiCode, new HashMap<String, Object>());
	}

}
